package com.demon.auto.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demon.auto.dao.UserDao;
import com.demon.auto.model.dto.UserDto;
import com.demon.auto.model.entity.UserEntity;
import com.demon.auto.model.vo.PageVo;
import com.demon.auto.model.vo.UserVo;
import com.demon.auto.service.UserService;
import com.demon.auto.utils.CommonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 用户信息
 *
 * @author huangrz
 * @version 1.0
 * @date 2025/02/13 17:08
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Boolean saveUserInfo(UserEntity user) {
        UserEntity oldUser = findByUsername(user.getUsername());
        if (oldUser != null) {
            // 用户名已存在
            if (!oldUser.getId().equals(user.getId())) {
                return null;
            }
            // 单独提供API修改
            user.setPassword(null);
            user.setEmail(null);

            return updateById(user);
        }
        // 密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return save(user);
    }

    @Override
    public UserEntity findByUsername(String username) {
        LambdaQueryWrapper<UserEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(UserEntity::getUsername, username);
        queryWrapper.eq(UserEntity::getValidFlag, true);
        return getOne(queryWrapper, false);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean clearUserToken(UserDto userDto) {
        LambdaUpdateWrapper<UserEntity> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(UserEntity::getValidFlag, true);
        if (userDto.getId() != null) {
            updateWrapper.eq(UserEntity::getId, userDto.getId());
        } else if (StringUtils.isNotBlank(userDto.getUsername())) {
            updateWrapper.eq(UserEntity::getUsername, userDto.getUsername());
        } else {
            return false;
        }

        updateWrapper.set(UserEntity::getAccessToken, null);
        updateWrapper.set(UserEntity::getUpdateTime, LocalDateTime.now());
        return update(updateWrapper);
    }

    @Override
    public PageVo<UserEntity> queryByPage(UserVo condition) {
        LambdaQueryWrapper<UserEntity> queryWrapper = Wrappers.lambdaQuery();
            if (condition.getId() != null) {
                queryWrapper.eq(UserEntity::getId, condition.getId());
            }
            if (condition.getValidFlag() != null) {
                queryWrapper.eq(UserEntity::getValidFlag, condition.getValidFlag());
            }
            if (StringUtils.isNotBlank(condition.getUsername())) {
                queryWrapper.like(UserEntity::getUsername, condition.getUsername());
            }
            if (StringUtils.isNotBlank(condition.getEmail())) {
                queryWrapper.like(UserEntity::getEmail, condition.getEmail());
            }
            if (condition.getLoginTimeBegin() != null && condition.getLoginTimeEnd() != null) {
                queryWrapper.between(UserEntity::getLastLoginTime, condition.getLoginTimeBegin(), condition.getLoginTimeEnd());
            }
            if (condition.getCreateTimeBegin() != null && condition.getCreateTimeEnd() != null) {
                queryWrapper.between(UserEntity::getCreateTime, condition.getCreateTimeBegin(), condition.getCreateTimeEnd());
            }
            if (condition.getUpdateTimeBegin() != null && condition.getUpdateTimeEnd() != null) {
                queryWrapper.between(UserEntity::getUpdateTime, condition.getUpdateTimeBegin(), condition.getUpdateTimeEnd());
            }
        return baseMapper.selectPage(condition, queryWrapper);
    }

    @Override
    public boolean updatePassword(String password) {
        return updateById(new UserEntity()
                .setId(CommonUtil.getCurrentUserId())
                .setPassword(passwordEncoder.encode(password)));
    }

    @Override
    public boolean updateEmail(String email) {
        return updateById(new UserEntity()
                .setId(CommonUtil.getCurrentUserId())
                .setEmail(email));
    }

}
